<script setup>
import { ref, onMounted } from 'vue'
import { sessionApi, treeTypesApi, selTypesApi, selBrandsApi, saveSpuApi, proSpusApi, oneSpuApi, pageSpusApi } from '@/commons/api'
import routes from '@/commons/router'
import Loader from '@/components/loader/Loader'
import TreeSel from '@/components/cascader/TreeSel'
import Selector from '@/components/select/Selector'
import { CScrollbar } from 'c-scrollbar'
import Msg from '@/components/message'
import Confirm from '@/components/confirm'
import Pager from '@/components/pager/Pager'
import Upload from '@/components/upload/Upload'
import SpuParam from '@/components/business/SpuParam'

const curKind = 1
const curState = 1

const loadShow = ref(false)

// 界面挂载前处理
onMounted(() => {
  // 获取用户会话信息
  checkAuth()
})

let myAuth = {
  saveAuth: false,
  procAuth: false
}
// checkAuth 获取权限
const checkAuth = async () => {
  loadShow.value = true
  try {
    const res = await sessionApi()
    if (res.code === import.meta.env.VITE_SUCCESS_CODE) {
      const userBtnCode = res.data.btnCodes
      myAuth = {
        saveAuth: userBtnCode.indexOf('1003020501') !== -1,
        procAuth: userBtnCode.indexOf('1003020502') !== -1
      }
      await treeTypes()
      await selTypes(1, '111111111111111111111')
      await page(0, 1)
    } else {
      localStorage.removeItem("token")
      Msg({ kind: 'error', txt: res.msg })
      routes.replace('/login')
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

const schRef = ref({
  kind: curKind,
  states: curState,
  brandId: '',
  brandName: '',
  brandCode: '',
  typeId: '',
  typeName: '',
  typeCode: '',
  keywords: '',
  offset: 0,
  limit: 20
})
const total = ref(0)
const curPage = ref(1)
const spuList = ref([])
const hasData = ref(false)
// page 列表展示
const page = async (offset, cur) => {
  schRef.value.offset = offset || 0
  curPage.value = cur || 1
  hasData.value = false
  const res = await pageSpusApi(schRef.value)
  if(res.code === import.meta.env.VITE_SUCCESS_CODE && res.data) {
    hasData.value = true
    total.value = res.data.total
    spuList.value = res.data.list
    idList.value = []
    checkList.value = []
    allCheck.value = false
    res.data.list.forEach(() => {
      checkList.value.push(false)
    })
  }
}

// search 筛选
const schShow = ref(false)
const search = () => {
  schShow.value = !schShow.value
}

// clrSch 重置搜索框
const clrSch = () => {
  schRef.value = {
    kind: curKind,
    states: curState,
    brandId: '',
    brandName: '',
    brandCode: '',
    typeId: '',
    typeName: '',
    typeCode: '',
    keywords: '',
    offset: 0,
    limit: 20
  }
  page(0, 1)
}

// 选择效果实现
const idList = ref([])
const checkList = ref([])
const allCheck = ref(false)
// checkAll 全选
const checkAll = () => {
  idList.value = []
  checkList.value = []
  allCheck.value = !allCheck.value
  if(allCheck.value) {
    spuList.value.forEach(item => {
      idList.value.push(item.spuId)
      checkList.value.push(true)
    })
  } else {
    spuList.value.forEach(() => {
      checkList.value.push(false)
    })
  }
}
// checkCurId 单选
const checkCurId = (idx, roleId) => {
  if(!checkList.value[idx]) {
    idList.value.push(roleId)
  } else {
    idList.value.splice(idList.value.findIndex(id => id === roleId), 1)
  }
  checkList.value[idx] = !checkList.value[idx]
}

const spuForm = ref({
  spuId: '',
  fstName: '',
  secName: '',
  spuCode: '',
  kind: '',
  brandId: '',
  brandName: '',
  brandCode: '',
  fstType: '',
  fstTypeName: '',
  fstTypeCode: '',
  secType: '',
  secTypeName: '',
  secTypeCode: '',
  thrType: '',
  thrTypeName: '',
  thrTypeCode: '',
  costs: '',
  oldPrice: '',
  price: '',
  prvdIds: '',
  fstImgId: '',
  fstImgName: '',
  fstImgUrl: '',
  fileIds: '',
  fileNames: '',
  fileUrls: '',
  visitNum: '',
  buyNum: '',
  cmtNum: '',
  grade: '',
  tagIds: '',
  remarks: '',
  paramList: []
})
// add 新增
const showModal = ref(false)
const add = () => {
  showModal.value = true
}
// update 修改
const update = async (spuId) => {
  const res = await oneSpuApi({ spuId })
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    spuForm.value = res.data
    showModal.value = true
  } else {
    Msg({ kind: 'info', txt: '暂无内容' })
  }
}
// save 保存提交
const save = async () => {
  let fstName = spuForm.value.fstName
  let spuCode = spuForm.value.spuCode
  let brandId = spuForm.value.brandId
  let fstType = spuForm.value.fstType
  let secType = spuForm.value.secType
  let thrType = spuForm.value.thrType
  if(fstName === '' || fstName.length > 50) {
    Msg({ kind: 'warn', txt: '名称不能为空，且长度不超过50个字符！' })
    return
  } else if(spuCode === '' || spuCode.length > 30) {
    Msg({ kind: 'warn', txt: '编码不能为空，且长度为30位的数字编码！' })
    return
  } else if(brandId === '' || brandId.length !== 21) {
    Msg({ kind: 'warn', txt: '请选择品牌！' })
    return
  } else if(fstType === '' || fstType.length !== 21) {
    Msg({ kind: 'warn', txt: '请选择一级分类！' })
    return
  } else if(secType === '' || secType.length !== 21) {
    Msg({ kind: 'warn', txt: '请选择二级分类！' })
    return
  } else if(thrType === '' || thrType.length !== 21) {
    Msg({ kind: 'warn', txt: '请选择三级分类！' })
    return
  }
  spuForm.value.sort = sort
  loadShow.value = true
  try {
    const res = await saveSpuApi(spuForm.value)
    if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
      closeModal()
      await page(0, 1)
      Msg({ kind: 'success', txt: '恭喜您，按钮信息保存成功！' })
    } else {
      Msg({ kind: 'error', txt: res.msg })
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

// closeModal 关闭弹出层，并重置表单数据
const closeModal = () => {
  showModal.value = false
  spuForm.value = {
    spuId: '',
    fstName: '',
    secName: '',
    spuCode: '',
    kind: '',
    brandId: '',
    brandName: '',
    brandCode: '',
    fstType: '',
    fstTypeName: '',
    fstTypeCode: '',
    secType: '',
    secTypeName: '',
    secTypeCode: '',
    thrType: '',
    thrTypeName: '',
    thrTypeCode: '',
    costs: '',
    oldPrice: '',
    price: '',
    prvdIds: '',
    fstImgId: '',
    fstImgName: '',
    fstImgUrl: '',
    fileIds: '',
    fileNames: '',
    fileUrls: '',
    visitNum: '',
    buyNum: '',
    cmtNum: '',
    grade: '',
    tagIds: '',
    remarks: '',
    paramList: []
  }
}

// process 处理
const process = async(states) => {
  if(!idList || idList.value.length===0) {
    Msg({ kind: 'warn', txt: '请至少选择一项再处理！' })
    return
  }
  Confirm('确定要处理选中的数据吗？').then(() => {
    proSpus(states)
  }).catch(() => {
    Msg({ kind: 'info', txt: "取消处理选中的数据！" })
  })
}
// proSpus 删除实现，分离出来防止调用时异步报错
const proSpus = async (states) => {
  let spuIds = idList.value.join(',')
  loadShow.value = true
  try {
    const res = await proSpusApi({ states, spuIds })
    if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
      await page(0, 1)
      Msg({ kind: 'success', txt: '恭喜您，信息删除成功！' })
    } else {
      Msg({ kind: 'error', txt: res.msg })
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

// 获取分类选择列表
const typeList = ref([])
const treeTypes = async () => {
  const res = await treeTypesApi({ kind: curKind })
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    typeList.value = res.data
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}

// 获取分类选择列表
const fstTypes = ref([])
const secTypes = ref([])
const thrTypes = ref([])
const selTypes = async (level, parentId) => {
  const res = await selTypesApi({ kind: curKind, parentId })
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    switch (level) {
      case 1:
        fstTypes.value = res.data
        break
      case 2:
        secTypes.value = res.data
        break
      case 3:
        thrTypes.value = res.data
    }
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}

// 获取品牌选择列表
const brandList = ref([])
const selBrands = async (typeId) => {
  const res = await selBrandsApi({ kind: curKind, typeId })
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    brandList.value = res.data
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}

// 赋值
const setValue = (item, kind) => {
  switch(kind) {
    case 1:
      schRef.value.typeId = item.selId
      schRef.value.typeName = item.selName
      schRef.value.typeCode = item.selCode
      selBrands(item.selId)
      break
    case 2:
      schRef.value.brandId = item.selId
      schRef.value.brandName = item.selName
      schRef.value.brandCode = item.selCode
      break
    case 3:
      spuForm.value.brandId = item.selId
      spuForm.value.brandName = item.selName
      spuForm.value.brandCode = item.selCode
      break
    case 4:
      spuForm.value.fstTypeId = item.selId
      spuForm.value.fstTypeName = item.selName
      spuForm.value.fstTypeCode = item.selCode
      selTypes(2, item.selId)
      break
    case 5:
      spuForm.value.secTypeId = item.selId
      spuForm.value.secTypeName = item.selName
      spuForm.value.secTypeCode = item.selCode
      selTypes(3, item.selId)
      break
    case 6:
      spuForm.value.thrTypeId = item.selId
      spuForm.value.thrTypeName = item.selName
      spuForm.value.thrTypeCode = item.selCode
      selBrands(item.selId)
      break
  }
}

// 回调获取上传文件的地址
const fileRef = ref({id: '', name: '', url: ''})
const fileList = ref([])
const setUrl = (kind, type, file) => {
  switch (kind) {
    case 1:
      fileRef.value = file
      break;
    case 2:
      fileList.value = file
      break;
  }
}

const setParams = (paramList) => {
  spuForm.value.paramList = paramList
}
</script>

<template>
  <div class="spu-a">
    <div class="spu-b">
      <div class="spu-c">
        <div v-if="myAuth.saveAuth" class="btn-pi mr15" title="新增" @click="add"><i class="iconfont">&#xea2d;</i> 新增</div>
        <div v-if="myAuth.procAuth" class="btn-de mr15" title="删除" @click="process(2)"><i class="iconfont">&#xea45;</i> 删除</div>
        <div v-if="myAuth.procAuth" class="btn-ds mr15" title="上架" @click="process(1)"><i class="iconfont">&#xea30;</i> 上架</div>
        <div class="btn-r mr15" title="筛选" @click="search"><i class="iconfont">&#xea49;</i></div>
        <div class="btn-r mr15" title="刷新" @click="page(0, 1)"><i class="iconfont">&#xea8c;</i></div>
      </div>
      <div class="spu-d"><i class="iconfont">&#xeaaa;</i> 当前位置：工作台 > 供应 > 商品管理 > 仓库中</div>
    </div>
    <div v-show="schShow" class="spu-e">
      <div class="mr15 mt10"><tree-sel :kind="1" :tree-list="typeList" :inboxed="true" :curName="schRef.typeName!=='' ? schRef.typeName+'['+schRef.typeCode+']' : ''" pre-name="分类" @setValue="setValue" /></div>
      <div class="mr15 mt10"><selector :kind="2" :sel-list="brandList" :inboxed="true" :cur-name="schRef.brandName ? schRef.brandName + '[' + schRef.brandCode + ']' : ''" pre-name="品牌" @setValue="setValue" /></div>
      <div class="mr15 mt10"><input type="text" v-model="schRef.keywords" maxlength="30" placeholder="请输入关键字" class="sch-ipt" /></div>
      <div class="spu-f mt10">
        <div class="btn-pi mr15" title="搜索" @click="page(0, 1)"><i class="iconfont">&#xea8e;</i> 搜索</div>
        <div class="btn-d" title="重置" @click="clrSch"><i class="iconfont">&#xea4f;</i> 重置</div>
      </div>
    </div>
    <div v-if="hasData">
      <table>
        <tbody>
          <tr>
            <th style="width: 10%;"><span @click="checkAll()" title="全选"><i :class="['iconfont', allCheck ? 'chked' : 'chk']" v-html="allCheck ? '&#xea3a;' : '&#xea46;'" /></span></th>
            <th style="width: 25%;">分类</th>
            <th style="width: 15%;">名称</th>
            <th style="width: 20%;">编码</th>
            <th style="width: 15%;">排序</th>
            <th style="width: 15%;">操作</th>
          </tr>
          <tr v-for="(curSpu, index) in spuList" :key="curSpu.spuId" class="tr-style">
            <td class="txt-center"><span @click="checkCurId(index, curSpu.spuId)" title="选择"><i :class="['iconfont', checkList[index] ? 'chked' : 'chk']" v-html="checkList[index]  ? '&#xe685;' : '&#xe686;'" /></span></td>
            <td class="txt-center">{{ curSpu.fstTypeName }}[{{ curSpu.fstTypeCode }}]/{{ curSpu.secTypeName }}[{{ curSpu.secTypeCode }}]/{{ curSpu.thrTypeName }}[{{ curSpu.thrTypeCode }}]</td>
            <td class="txt-center">{{ curSpu.fstName }}</td>
            <td class="txt-center">{{ curSpu.spuCode }}</td>
            <td class="txt-center">{{ curSpu.cost }}元</td>
            <td class="txt-center">
              <span v-if="myAuth.saveAuth" class="cl-warn" title="修改" @click="update(curSpu.spuId)"><i class="iconfont">&#xea48;</i> 修 改</span>
            </td>
          </tr>
        </tbody>
      </table>
      <pager v-if="hasData" :limit="schRef.limit" :total="total" :page="curPage" @turn="page" />
    </div>
    <div v-else class="no-data">暂无内容</div>

    <!-- 新增、修改弹出层 -->
    <transition name="fade-mod" appear>
      <div v-if="showModal" class="modal-backdrop">
        <c-scrollbar>
          <div class="modal" style="width: 1040px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont">&#xea54;</i> 保存信息</div>
              <div class="header-right" @click="closeModal()"><i class="iconfont fs22">&#xea7f;</i></div>
            </div>
            <div class="modal-body">
              <div>
                <div class="ipt-title"><span class="required">*</span>一级标题</div>
                <div><input type="text" v-model="spuForm.fstName" maxlength="80" placeholder="请输入一级标题" class="ipt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>二级标题</div>
                <div><input type="text" v-model="spuForm.secName" maxlength="80" placeholder="请输入二级标题" class="ipt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>商品编码</div>
                <div><input type="text" v-model="spuForm.spuCode" maxlength="10" placeholder="请输入编码" class="ipt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>分类品牌</div>
                <div class="spu-g">
                  <div class="spu-h"><selector :kind="4" :sel-list="fstTypes" :inboxed="true" :cur-name="spuForm.fstTypeName!=='' ? spuForm.fstTypeName+'['+spuForm.fstTypeCode+']' : ''" pre-name="一级分类" @setValue="setValue" /></div>
                  <div class="spu-h"><selector :kind="5" :sel-list="secTypes" :inboxed="true" :cur-name="spuForm.secTypeName!=='' ? spuForm.secTypeName+'['+spuForm.secTypeCode+']' : ''" pre-name="二级分类" @setValue="setValue" /></div>
                  <div class="spu-h"><selector :kind="6" :sel-list="thrTypes" :inboxed="true" :cur-name="spuForm.thrTypeName!=='' ? spuForm.thrTypeName+'['+spuForm.thrTypeCode+']' : ''" pre-name="三级分类" @setValue="setValue" /></div>
                  <div class="spu-h"><selector :kind="3" :sel-list="brandList" :inboxed="true" :cur-name="spuForm.brandName!=='' ? spuForm.brandName+'['+spuForm.brandCode+']' : ''" pre-name="品牌" @setValue="setValue" /></div>
                </div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>价格</div>
                <div class="spu-g">
                  <div class="spu-h"><input type="number" v-model="spuForm.costs" maxlength="10" placeholder="请输入成本价" class="ipt" /></div>
                  <div class="spu-h"><input type="number" v-model="spuForm.oldPrice" maxlength="10" placeholder="请输入原价" class="ipt" /></div>
                  <div class="spu-h"><input type="number" v-model="spuForm.price" maxlength="10" placeholder="请输入销售价" class="ipt" /></div>
                </div>
              </div>
              <div>
                <div class="ipt-title">评分数量</div>
                <div class="spu-g">
                  <div class="spu-h"><input type="number" v-model="spuForm.grade" maxlength="10" placeholder="请输入评分" class="ipt" /></div>
                  <div class="spu-h"><input type="number" v-model="spuForm.visitNum" maxlength="10" placeholder="请输入访问量" class="ipt" /></div>
                  <div class="spu-h"><input type="number" v-model="spuForm.buyNum" maxlength="10" placeholder="请输入下单量" class="ipt" /></div>
                  <div class="spu-h"><input type="number" v-model="spuForm.cmtNum" maxlength="10" placeholder="请输入评论数量" class="ipt" /></div>
                </div>
              </div>
              <div>
                <div class="ipt-title">图片素材</div>
                <div class="spu-g">
                  <div class="spu-h"><upload :kind="1" :types="1" :file="fileRef" @setUrl="setUrl" /></div>
                  <div><upload :kind="3" :types="2" :file="fileList" @setUrl="setUrl" /></div>
                </div>
              </div>
              <div>
                <div class="ipt-title">商品参数</div>
                <spu-param :kind="curKind" :paramList="spuForm.paramList" @setParams="setParams" />
              </div>
              <div>
                <div class="ipt-title">描述</div>
                <div><textarea v-model="spuForm.remarks" class="desc-txt"></textarea></div>
              </div>
            </div>
            <div class="modal-footer">
              <div class="btn-pi mr15" @click="save"><i class="iconfont">&#xea90;</i> 保存</div>
              <div class="btn-d" @click="closeModal"><i class="iconfont">&#xea4f;</i> 取消</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>
    <loader :loadShow="loadShow" />
  </div>
</template>

<style scoped>
.spu-a {padding: 10px;}
.spu-b {padding: 0 20px 10px 20px; display: flex; display: -webkit-flex;}
.spu-c {display: inline-flex; display: -webkit-inline-flex;}
.spu-d {flex-grow: 1; text-align: right; padding-top: 10px; color: #666;}
.spu-e {border: 1px dashed #DDD; padding: 5px 15px 15px 15px; display: flex; display: -webkit-flex; flex-wrap: wrap; margin-bottom: 10px;}
.spu-f {display: inline-flex; display: -webkit-inline-flex;}
.spu-g {width: 100%; display: flex; display: -webkit-flex;}
.spu-h {width: 25%; padding: 0 5px;}
.spu-i {width: 100%; display: flex; display: -webkit-flex; justify-content: space-around;}
</style>